"""
导入drg记录
"""
import json
import re

import pdfplumber

import common
import drg_mcc_exclude
import drg_mcc_exclude_table

__TAG = 'Drg2'
__FIELDS = ['Group', 'IcdCode','Exclude']
__SERVER = common.ServerRemoteRelease
__INPUT = '/home/zhujianfeng/文档/drgs_2_2.pdf'
__OUTPUT = ['out/drg.txt', 'out/NoDrg.txt']

def try_read_page(page):
    page_width = page.width
    left_bbox = (0, 0, page_width / 2, page.height - 64)
    right_bbox = (page_width / 2, 0, page_width, page.height - 64)
    re_text = page.crop(left_bbox).extract_text()
    re_text += "\n"
    re_text += page.crop(right_bbox).extract_text()
    return re_text


def extract_group_code():
    txt = ""
    with pdfplumber.open(__INPUT) as pdf:
        # page = pdf.pages[1205]
        for page in pdf.pages:
            print(page.page_number)
            if page.page_number < 65 or page.page_number > 1157:
                continue
            txt += try_read_page(page)
    with open(__OUTPUT[0], 'w', encoding='utf-8') as file:
        file.write(txt)

def extract_no_group_code():
    txt = ""
    with pdfplumber.open(__INPUT) as pdf:
        # page = pdf.pages[1205]
        for page in pdf.pages:
            print(page.page_number)
            if page.page_number < 1158 or page.page_number > 1207:
                continue
            txt += try_read_page(page)
    with open(__OUTPUT[1], 'w', encoding='utf-8') as file:
        file.write(txt)

def post_drg_records():
    drg_code_pattern = re.compile(r'^[A-Z]{2}\d')
    icd_10_code_pattern = re.compile(r'^[A-Z]\d+(\.\d+)(x\d+)*(\+\S+\*)*')
    icd_9_code_pattern = re.compile(r'^\d+\.\d+(x\d+)?')
    with open(__OUTPUT[0], 'r', encoding='utf-8') as file:
        records = []
        for line in file:
            match = re.search(drg_code_pattern, line.strip())
            if match:
                drg_code = match.group()  # 使用group()方法提取匹配结果
                # print(drg_code)
            match2 = re.search(icd_10_code_pattern, line.strip())
            if match2:
                icd_code = match2.group()  # 使用group()方法提取匹配结果
                # print(icd_code)
                records.append({
                    __FIELDS[0]: drg_code,
                    __FIELDS[1]: icd_code
                })
            match3 = re.search(icd_9_code_pattern, line.strip())
            if match3:
                icd_code = match3.group()  # 使用group()方法提取匹配结果
                # print(icd_code)
                records.append({
                    __FIELDS[0]: drg_code,
                    __FIELDS[1]: icd_code
                })
            if len(records) > 0 and len(records) % 100 == 0:
                msg = json.dumps({
                    "fields": __FIELDS,
                    "records": records
                }, ensure_ascii=False)
                print(msg)
                common.batch_add(__TAG, msg, __SERVER)
                records.clear()
        if len(records) > 0:
            msg = json.dumps({
                "fields": __FIELDS,
                "records": records
            }, ensure_ascii=False)
            print(msg)
            common.batch_add(__TAG, msg, __SERVER)


def post_no_drg_records():
    icd_10_code_pattern = re.compile(r'^[A-Z]\d+(\.\d+)(x\d+)*(\+\S+\*)*')
    icd_9_code_pattern = re.compile(r'^\d+\.\d+(x\d+)?')
    drg_code = '000'
    with open(__OUTPUT[1], 'r', encoding='utf-8') as file:
        records = []
        for line in file:
            match2 = re.search(icd_10_code_pattern, line.strip())
            if match2:
                icd_code = match2.group()  # 使用group()方法提取匹配结果
                # print(icd_code)
                records.append({
                    __FIELDS[0]: drg_code,
                    __FIELDS[1]: icd_code
                })
            match3 = re.search(icd_9_code_pattern, line.strip())
            if match3:
                icd_code = match3.group()  # 使用group()方法提取匹配结果
                # print(icd_code)
                records.append({
                    __FIELDS[0]: drg_code,
                    __FIELDS[1]: icd_code
                })
            if len(records) > 0 and len(records) % 100 == 0:
                msg = json.dumps({
                    "fields": __FIELDS,
                    "records": records
                }, ensure_ascii=False)
                print(msg)
                common.batch_add(__TAG, msg, __SERVER)
                records.clear()
        if len(records) > 0:
            msg = json.dumps({
                "fields": __FIELDS,
                "records": records
            }, ensure_ascii=False)
            print(msg)
            common.batch_add(__TAG, msg, __SERVER)


def format_code():
    last_index = 0
    has_more = True
    page_index = 1
    while has_more:
        data = {
            "fields": __FIELDS,
            "pageIndex": page_index,
            "lastIndex": last_index,
            "pageSize": 200,
            "filters": [
                {"cmd": 12, "args": ["IcdCode", "+"]}
            ]
        }
        data = json.dumps(data, ensure_ascii=False)
        response_data = common.page(__TAG, data, server=__SERVER)
        arm = json.loads(response_data)
        last_index = arm['data']['lastIndex']
        has_more = len(arm['data']['data']) >= 200
        actions = []
        for record in arm['data']['data']:
            rec_id = record['_id']
            code = record['IcdCode'].replace('\n', '').replace('+', '†')
            # print(code)
            action = {
                'action': 23,
                'tag': 'IcdCode',
                '_id': int(rec_id),
                'fv': code
            }
            actions.append(action)
        if len(actions) > 0:
            edit_message = {'actions': actions}
            edit_message = json.dumps(edit_message, ensure_ascii=False)
            print(edit_message)
            common.batch_modify(__TAG, edit_message, server=__SERVER)
        page_index += 1

def __find_code_and_edit_exclude(code:str, ex_codes):
    actions = []
    data = {
        "fields": __FIELDS,
        "pageIndex": 1,
        "lastIndex": 0,
        "pageSize": 200,
        "filters": [
            {"cmd": 11, "args": ["IcdCode", code]}
        ]
    }
    data = json.dumps(data, ensure_ascii=False)
    response_data = common.page(__TAG, data, server=__SERVER)
    arm = json.loads(response_data)
    for record in arm['data']['data']:
        rec_id = record['_id']
        action = {
            'action': 23,
            'tag': __FIELDS[2],
            '_id': int(rec_id),
            'fv': ex_codes
        }
        actions.append(action)
    if len(actions) > 0:
        edit_message = {'actions': actions}
        edit_message = json.dumps(edit_message, ensure_ascii=False)
        print(edit_message)
        common.batch_modify(__TAG, edit_message, server=__SERVER)


def edit_exclude():
    table_code_map = drg_mcc_exclude_table.export_map()
    code_table_map = drg_mcc_exclude.export_map()
    for key, value in code_table_map.items():
        print(key)
        __find_code_and_edit_exclude(key, table_code_map[value[0]])


if __name__ == '__main__':
    # pdf_to_text()
    # extract_code()
    # extract_no_group_code()
    # post_no_drg_records()
    edit_exclude()
